#include "main.h"
int ListInitiate(LNode **head){
    *head=(LNode *)malloc(sizeof(LNode));
    if(*head==NULL){
        return 1;
    }
    (*head)->next=NULL;
    return 0;
}
int ListLength(LNode *head){
    int length=0;
    LNode *current=head->next;
    while(current!=NULL){
        length++;
        current=current->next;
    }
    return  length;
}
int ListInsert(LNode *head,int i,DataType x){
    LNode *current=head;
    for (int k = 0; k <i&&current!=NULL ; k++) {
        current=current->next;
    }
    if(current==NULL){
        return 1;
    }
    LNode *newNode=(LNode *) malloc(sizeof(LNode));
    if (newNode ==NULL){
        return 1;
    }
    newNode->data=x;
    newNode->next=current->next;
    current->next=newNode;
    return  0;
}
int ListDelete(LNode *head, int i, int *x) {
    if (head == NULL || head->next == NULL)
        return 1; // Empty list or invalid head node

    int length = ListLength(head); // Get the list length
    if (i < 0 || i >= length)
        return 1; // Index out of range

    LNode *current = head;
    for (int k = 0; k < i && current->next != NULL; k++) {
        current = current->next;
    }

    if (current->next == NULL) // If position i is out of range
        return 1;

    LNode *temp = current->next;
    *x = temp->data;
    current->next = temp->next;
    free(temp); // Free memory of the deleted node

    // Decrease the list length
    length--;
    return 0;
}


int Destroy(LNode **head){
    LNode *current=*head;
    LNode *next;
    while (current !=NULL){
        next =current->next;
        free(current);
        current=next;
    }
    *head=NULL;
    return 0;
}
int ListGet(LNode *head, int i, DataType *x) {
    LNode *current = head->next;
    for (int k = 0; k < i && current != NULL; k++) {
        current = current->next;
    }
    if (current == NULL) {
        return 1; // Position not found
    }
    *x = current->data;
    return 0; // Success
}

int main(){
    LNode *head;
    int i,x;
    if(ListInitiate(&head)==1){
        printf("Error：Memory allocation failed");
        return 1;
    }
    x=5;
    for (int i = 0; i <10 ; ++i) {
        if(ListInsert(head,i,i+1)==1){
            printf("Error: insert falied\n");
            return 1;
        }

    }
    if (ListDelete(head, 4, &x) == 1) {
        printf("Deletion failed\n");
        return 1;
    } else {
        printf("Deleted element: %d\n", x);
    }

    int currentLength = ListLength(head);
    printf("Current list length: %d\n", currentLength);


    for (int i =0;i < ListLength(head) ; ++i) {
        if(ListGet(head,i ,&x)==1){
            printf("get falied\n");
            return 1;
        } else{
            printf("%d  ",x);
        }


    }printf("\n");
    if(Destroy(&head)==1){
        printf("error:destuction felied\n");

        return 1;
    }

    return  0;
}